package com.aepryus.loom;

import java.util.*;
import javax.servlet.http.*;

public class Trace {
	private Controller controller;
	private Stack<String> back;
	private Stack<String> fore;
	private String currentView;
	private boolean scrolling;
	private boolean sneaking;

	public Trace (Controller controller) {
		this.controller = controller;
		back = new Stack<String>();
		fore = new Stack<String>();
		scrolling = false;
	}

	public void trace (String server,String view,String query) {
		String url = server+"?view="+view+(query!=null?query:"");
		if (back.size()==0 || !url.equals(back.peek())) {
			currentView = view;
			back.push(url);
			if (!scrolling)
				fore.removeAllElements();
		}
		scrolling = false;
		sneaking = false;
	}
	public void sneak () {
		scrolling = false;
		sneaking = true;
	}
	public String back (HttpServletRequest request) {
		scrolling = true;
		if (back.size() == 0) return controller.getAboutURL();
		if (!sneaking)
			fore.push(back.pop());
		else
			sneaking = false;
		if (back.size() == 0) return controller.getAboutURL();
		return back.pop();
	}
	public String fore (HttpServletRequest request) {
		scrolling = true;
		sneaking = false;
		if (fore.size() != 0)
			return fore.pop();
		if (back.size() != 0)
			return back.peek();
		return controller.getAboutURL();
	}
	public String getCurrentURL () {
		if (back.size() == 0) return controller.getAboutURL();
		return back.peek();
	}
	public String getCurrentView () {
		return currentView;
	}
}

/* Junk Yard ===================================================================
	public void trace (HttpServletRequest request) {
		if ("POST".equals(request.getMethod())) return;
		if (tracing) {
			currentView = request.getParameter("view");
			back.push(request.getRequestURI()+"?"+request.getQueryString());
		    tracing = false;
		} else {
			if (request.getParameter("notrace") != null) return;
	    	if (currentView == null || !currentView.equals(request.getParameter("view")) || request.getParameter("trace")!=null) {
				currentView = request.getParameter("view");
				back.push(request.getRequestURI()+"?"+request.getQueryString());
				fore.removeAllElements();
			} else if (currentView.equals(request.getParameter("view"))) {
				back.pop();
				back.push(request.getRequestURI()+"?"+Trace.stripAction(request.getQueryString()));
				fore.removeAllElements();
			}
		}
	}
	private static String stripAction (String query) {
		if (query == null) return query;
		StringBuffer sb = new StringBuffer();
		int n = query.indexOf("&action=");
		if (n == -1)
			return query;
		sb.append(query.substring(0,n));

		n = query.indexOf("&",query.indexOf("&action")+1);
		if (n != -1)
			sb.append(query.substring(n));

		return sb.toString();
	}
============================================================================= */